<template>
  <q-tabs v-model="data.tab" active-color="primary" align="left">
    <template v-for="(account, index) in accounts" :key="index">
      <q-tab :name="index" :label="account.nickname">
        <q-badge color="red" rounded floating v-if="badges[account.userid]">
          <template v-if="badgeEllipsis && badges[account.userid] > 99">
            99+
          </template>
          <template v-else>
            {{ badges[account.userid] }}
          </template>
        </q-badge>
      </q-tab>
    </template>
  </q-tabs>
</template>

<script>
import { defineComponent, reactive, computed, watch, inject } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useStore } from "vuex";

export default defineComponent({
  name: "ComponentsAccountsTabsVue",
  props: {
    enable: Boolean,
    modelValue: Number,
    account: Object,
    badges: {
      type: Object,
      default: () => ({}),
    },
    badgeEllipsis: Boolean,
  },
  emits: ["update:modelValue", "update:account"],
  setup(props, { emit }) {
    const bus = inject("bus");
    const $store = useStore();
    const $router = useRouter();
    const $route = useRoute();
    const accounts = computed(() => $store.getters["persisted/accounts"]);

    const data = reactive({
      tab: computed({
        get: () => props.modelValue,
        set: (val) => {
          emit("update:modelValue", val);
          emit("update:account", accounts.value[val]);
        },
      }),
      account: computed(() => accounts.value[data.tab]),
    });

    if (props.account || $route.query.id) {
      const id = $route.query.id || props.account.userid;
      $store.getters["persisted/accounts"].find((el, i) => {
        if (id == el.userid) {
          data.tab = i;
          return true;
        }
      });
    }
    watch(
      () => data.account,
      (val) => {
        $router.replace({ query: { id: val.userid } });
        emit("update:account", val);
        bus.emit("toggleAccountTab", val);
      },
      { immediate: true }
    );
    return { data, accounts };
  },
});
</script>
